class Pagination{
    async init(){
      this.goodsList = $("#goods_list");
      this.next = $("#next");
      this.prev = $("#prev");
      this.btnList = [];
      // this.url = "../json/cake.json";
      // this.data =  {
      //       subject_id:5581,
      //       page:1,
      //       size:100
      // };
      // 新内容 
      // 一页显示多少个;
      this.renderNum = 12;
      // 页码;
      this.page = 1;
      this.page_total = 0;
      this.res = await this.loadData(); 
      this.render();
      this.renderPageBtn();

      this.bindEvent();
    }
    bindEvent(){
      this.next.addEventListener("click",this.nextPage.bind(this));
      this.prev.addEventListener("click",this.prevPage.bind(this));
      this.btnList.forEach( (ele,index) => {
            ele.addEventListener("click",this.toPage.bind(this,index+1))
      })
      this.next.parentNode.addEventListener("click",this.reRender.bind(this))
    }
    async loadData(){
      let res = await xhrGet(this.url,this.data);
      res = JSON.parse(res);
      return res;
    }

     xhrGet(url,data){
      return new Promise((resolve,reject)=>{
        var xhr = new XMLHttpRequest();
        if(typeof data !== "function" && data instanceof Object){
              // 拼接字符串; 
              var _arr = [];
              for(var key in data){
                    _arr.push( `${key}=${data[key]}`)
              }
              var _symbol = /\?/.test(url) ? "&" : "?";
              url += _symbol + _arr.join("&")
        }     
        xhr.open("GET",url);
        xhr.send(null);
        xhr.onreadystatechange = function(){
              if(xhr.readyState === 4 && xhr.status === 200) 
              resolve(xhr.responseText);
        }
      })
  }


    reRender(){
        // 添加对应位置的active;
        this.btnList.forEach( (ele,index) => {
            if(index + 1 === this.page){
                  ele.className = "active";
            }else{
                  ele.className = "";
            }
        })
        this.render();
    }
    nextPage(){

      if( this.page === this.page_total){
            return false;
      }else{
            this.page ++;
      }
    }
    prevPage(){
      if( this.page === 1){
            return false;
      }else{
            this.page --;
      }
    }
    toPage(index){      
       this.page = index;
    }
    renderPageBtn(){
      this.page_total = Math.ceil( this.res.goods_list.length / this.renderNum);

      let btnWrap = document.createDocumentFragment();
      for(var i = 1 ; i <= this.page_total ; i ++){
            let li = document.createElement("li");
            let a = document.createElement("a");
            a.innerHTML = i;
            li.appendChild(a);

            if(i === this.page){
                 li.className = "active" ;
            }
            btnWrap.appendChild(li);
            this.btnList.push(li);
      }     

      this.next.parentNode.insertBefore(btnWrap,this.next);


    }
    render(){
            // console.log(this.res);
            let goods_list = this.res.goods_list;
            let html = "";

            for(var i = this.renderNum * (this.page - 1) ; i < this.renderNum * this.page ; i ++){
                  let item = goods_list[i];
                  if(!item) continue;
                  html +=  `<li class="goods-item">
                              <div class="img-box">
                                    <img src="${item.hd_thumb_url}" 
                                    data-src="${item.hd_thumb_url}"
                                    alt="">
                              </div>
                              <div class="title-box">
                                    <p>${item.goods_name}</p>
                              </div>
                              <div class="detail-box">
                                    <div class="price-box">
                                          <span class="new">
                                          ￥${(item.normal_price/100).toFixed(2)}
                                          </span>
                                          <span class="old" style="text-decoration:line-through">
                                                ￥${(item.market_price/100).toFixed(2)}
                                          </span>
                                    </div>
                                    <div class="bought">
                                          ${item.sales_tip}
                                    </div>
                              </div>
                  </li>`
            }
            this.goodsList.innerHTML = html;
    }
}

function $(selector){
return document.querySelector(selector);
}

var pag = new Pagination();
pag.init();

// page 1    2       3         4                  n 
// 0 ~ 7 ; 8 ~ 15  16 ~ 23  24 ~ 31   8 * (n - 1) ~  8 * n  - 1;
// 